import React, { useEffect, useState, useRef} from "react";
import {View, Text, StyleSheet, Alert, TouchableOpacity, Image} from "react-native";
import { Swipeable } from 'react-native-gesture-handler';
import avator from "@/assets/images/me/avator.png"
import { formatConversionTime, getConversationContent } from "@/utils/ImCommon"
import { MessageItem } from "open-im-sdk-rn/lib/typescript/types/entity";
import { router } from "expo-router";
import { useConversationStore } from "@/hooks/im/conversation";
import OpenIMSDKRN from "open-im-sdk-rn";
import { v4 as uuidv4 } from "uuid";

const NewRenderComponent = function ({ items }) {

    const { item } = items;

    const [openItemId, setOpenItemId] = useState(null); // 记录当前打开的项的 ID
    const swipeableRefs = useRef([]); // 用于保存 Swipeable 组件的引用

    const updateCurrentConversation = useConversationStore((state) => state.updateCurrentConversation);
    // console.log('updateCurrentConversation', item);

    const formattedMessage = () => {
        let parsedMessage: MessageItem | undefined;
        try {
            parsedMessage = JSON.parse(item.latestMsg);
        } catch (e) {
            console.log("parsedMessage error");
        }
        if (!parsedMessage) return "";
        return getConversationContent(parsedMessage);
    };



    const renderRightActions = (id) => (
        <TouchableOpacity style={styles.deleteButton} onPress={() => handleDelete(id)}>
            <Text style={styles.deleteText}>删除</Text>
        </TouchableOpacity>
    );

    const handleDelete = (conversationID: string) => {
        Alert.alert(
            '删除确认',
            '您确定要删除这条消息吗？',
            [
                {
                    text: '取消',
                    style: 'cancel',
                },
                {
                    text: '确定',
                    onPress: () => {
                        console.log('conversationID', conversationID);
                        // OpenIMSDKRN.deleteConversationAndDeleteAllMsg(conversationID, uuidv4());
                    },
                },
            ],
            { cancelable: false }
        );
    };

    const goChat = function (item: any) {
        console.log('goChat', item);
        updateCurrentConversation({ ...item });
        router.push("/chat/123")
    };

    return (
        <Swipeable
            ref={(ref) => (swipeableRefs.current[item.conversationID] = ref)}
            renderRightActions={() => renderRightActions(item.conversationID)}
            onSwipeableWillOpen={() => {
                // 关闭其他打开的项
                if (openItemId && openItemId !== item.conversationID) {
                    swipeableRefs.current[openItemId]?.close();
                }
                setOpenItemId(item.conversationID); // 设置当前打开的项 ID
            }}
            onSwipeableWillClose={() => {
                setOpenItemId(null); // 清空当前打开的项 ID
            }}
        >
            <TouchableOpacity style={styles.chatItem} onPress={() => goChat(item)}>
                <Image source={avator} style={styles.avatar} />
                <View style={styles.textContainer}>
                    <View style={styles.bodyContent}>
                        <View style={styles.chatName}>
                            <Text style={styles.chatNameText}>{item.showName}</Text>
                        </View>
                        <View style={styles.chatTime}>
                            <Text style={styles.chatTimeText}>{ formatConversionTime(item.latestMsgSendTime) }</Text>
                        </View>
                    </View>
                    <View style={styles.bodyFooter}>
                        <View style={styles.message}>
                            <Text style={styles.messageText}>{ formattedMessage(item?.latestMsg) }</Text>
                        </View>
                        {
                            item.unreadCount > 0 && (
                                <View style={styles.unRead}>
                                    <Text style={styles.unReadText}>{ item.unreadCount || "" }</Text>
                                </View>
                            )
                        }

                    </View>
                </View>
            </TouchableOpacity>
        </Swipeable>
    )
};

export default NewRenderComponent;

const styles = StyleSheet.create({
    chatItem: {
        flexDirection: 'row',
        paddingHorizontal: 12,

        alignItems: 'center',
    },
    avatar: {
        width: 42,
        height: 42,
        borderRadius: 25,
        marginRight: 10,
    },
    textContainer: {
        flex: 1,
        borderBottomWidth: 0.3,
        paddingVertical: 14,
        borderBottomColor: "#E4E6EC"
    },
    name: {
        fontSize: 16,
        fontWeight: 'bold',
    },
    message: {
        color: '#777',
        marginTop: 5,
    },
    separator: {
        height: 1,
        backgroundColor: '#eee',
    },
    deleteButton: {
        backgroundColor: '#FB4B34',
        justifyContent: 'center',
        alignItems: 'center',
        width: 60,
    },
    deleteButtonText: {
        color: 'white',
        fontWeight: 'bold',
    },
    bodyContent: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between"
    },
    bodyFooter: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between"
    },
    chatName: {},
    chatNameText: {
        fontSize: 14,
        fontWeight: "bold",
        color: "#2A2B30"
    },
    chatTime: {},
    chatTimeText: {
        color: "#9C9EAC",
        fontSize: 12,
    },
    messageText: {
        color: "#9C9EAC",
        fontSize: 12,
    },
    unRead: {
        height: 16,
        marginTop: 5,
        borderRadius: 50,
        paddingHorizontal: 5,
        backgroundColor: "#FB4B34",
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center"
    },
    unReadText: {
        color: "#fff",
        fontSize: 12,
    },
    deleteText: {
        color: '#fff',
        fontWeight: 'bold',
    },
});
